//
//  MEGLView.m
//  MapEditor
//
//  Created by Eric on 3/5/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "MEGLView.h"
#import "MEBox2dLayer.h"
#import "MEController.h"
#import "MEStageTabItemView.h"

@implementation MEGLView
@synthesize editStageLayer;
-(void)dealloc{
    self.editStageLayer = nil;
    [super dealloc];
}

- (void) awakeFromNib
{
    [super awakeFromNib];
	[self registerForDraggedTypes:[NSArray arrayWithObjects:NSStringPboardType, nil]];
    //[self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
    
}

- (void)rightMouseDown:(NSEvent *)event{   
    MEScene* scene = [MEScene scene];
    [scene.layer rightClick:event];
}


#pragma mark Drag
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
    if ([MEScene scene].layer != editStageLayer) {
        return NSDragOperationNone;
    }
	return NSDragOperationCopy;  
    //return NSDragOperationEvery;
}
// Work around a bug from 10.2 onwards
- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
{
	return NSDragOperationEvery;
}

// Stop the NSTableView implementation getting in the way
- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
{
	return [self draggingEntered:sender];
}

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
    NSPoint np = [sender draggingLocation];
    np = [self convertPoint:np fromView:nil];
    CGPoint p = NSPointToCGPoint(np);
    
	NSPasteboard *pboard = [sender draggingPasteboard];
	if ([[pboard types] containsObject:NSStringPboardType])
	{
        NSInteger sid = [[pboard stringForType:NSStringPboardType] integerValue];
        MEPrototype* prototype = [[MEPrototypeMgr instance] prototypeWithSid:sid];
        
        MEController* ctrl = [MEController instance];
        NSIndexSet* index = [ctrl.layersPane selectionIndexes];
        NSInteger currentIndex = [index firstIndex];
        if (currentIndex != NSNotFound){
            MEEditStageSprite* spt = [MEEditStageSprite sprite:prototype];
            spt.positionForBody = p;
            spt.sid = ++ editStageLayer.spriteSidCount;
            [editStageLayer addSprite:spt];
            
            ((MEStageTabItemView*)ctrl.stageTabView.selectedTabViewItem.view).sidCountField.integerValue = editStageLayer.spriteSidCount;
        }
        [pboard clearContents];
        return YES;
    }
    return NO;
}


@end
